/**
 * Copyright 2019-2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "framework/graph/core/optimize/schedule/graph_pass_list.h"

#include <vector>

#include "infra/base/securestl.h"
#include "framework/graph/core/optimize/schedule/graph_pass.h"

namespace hiai {
class GraphPassListImpl : public GraphPassList {
private:
    void Add(std::unique_ptr<GraphPass> pass) override;
    OptimizeStatus Optimize(ge::ComputeGraph& graph) override;

private:
    std::vector<std::unique_ptr<GraphPass>> passes_;
};

void GraphPassListImpl::Add(std::unique_ptr<GraphPass> pass)
{
    passes_.emplace_back(std::move(pass));
}

OptimizeStatus GraphPassListImpl::Optimize(ge::ComputeGraph& graph)
{
    OptimizeStatus passStatus = OptimizeStatus::OPTIMIZE_NOT_CHANGED;
    for (const auto& pass : passes_) {
        auto ret = pass->Run(graph);
        if (ret == OptimizeStatus::OPTIMIZE_FAILED) {
            return OptimizeStatus::OPTIMIZE_FAILED;
        } else if (ret == OptimizeStatus::OPTIMIZE_CHANGED) {
            passStatus = OptimizeStatus::OPTIMIZE_CHANGED;
        }
    }

    return passStatus;
}

std::unique_ptr<GraphPassList> GraphPassList::Make()
{
    return make_unique_nothrow<GraphPassListImpl>();
}
} // namespace hiai